<template>
	<div class="layout-flex">
		<FastFilter @search="toRefresh" @reset="resetList">
			<template v-slot:leftFilters>
				<pop-cascader
					@query-list="searchCategory"
					:options="state.FBAlist"
					v-model="state.queryForm.whIds"
					placeholder="FBA仓库"
					:confirmDatatype="'2'"
					class="mr10 w180"
				/>

				<CategorySelect @change="handleSearch($event, 'skuCategoryList')" v-model="state.queryForm.skuCategoryList"/>
				<FunctionalSelect
					v-model="state.queryForm.skuBrandList"
					:optionFormat="{
						key: 'brandId',
						label: 'brandName',
					}"
					useRadio
					:options="state.skuBrandList"
					placeholder="产品品牌"
					@query-list="handleSearch($event, 'skuBrandList')"
					class="w180"
				/>
				<FunctionalSelect
					v-model="state.queryForm.deliveryChannelList"
					:options="state.deliveryChannelList"
					:optionFormat="{
						key: 'value',
						label: 'label',
					}"
					placeholder="配送方式"
					@query-list="handleSearch($event, 'deliveryChannelList')"
					class="w180"
				/>
				<UserSelect @change="handleSearch($event, 'saleDutyUidList')" v-model="state.queryForm.saleDutyUidList" title="销售负责人" class="w180" />
				<ComboSearch
					:options="state.comboSearchOpt"
					:prefixSelect="'skuCode'"
					@search="handleComboSearch($event, 'searchDto')"
					ref="comboSearchRef"
				/>
			</template>
			<template #result>
				<FilterTag
					v-for="(item, index) in FilterTagOption"
					:key="index"
					:show="item.key()"
					:label="item.label()"
					:value="item.value()"
					@close="closeTag(item.clear)"
				/>
			</template>
		</FastFilter>
		<div class="layout-padding">
			<FastTableHandle @queryTable="toRefresh(false)">
				<template v-slot:leftBtns>
					<span v-if="state.checkedRows.length > 0" style="color: #a6abb4" class="ml10">
						已选 <span style="color: #005bf5"> {{ state.checkedRows.length }} </span>条记录
					</span>
				</template>
				<template v-slot:rightWrapper>
					<el-checkbox v-model="state.queryForm.isHideZero" true-label="1" false-label="0" label="隐藏0库存数据" size="large" @change="toRefresh" />
					<el-icon @click="toExport">
						<Download />
					</el-icon>
					<el-icon>
						<Setting @click="columnsSettingRef.openDialog()" />
					</el-icon>
				</template>
			</FastTableHandle>
			<table-layout
				:header-cell-style="{ color: '#000' }"
				show-summary
				:summary-method="getSummaries"
				:query-form="state.queryForm"
				border
				ref="dataTableRef"
				:fetch-list="amazonFbaInventoryPage"
				@mouseEnterCell="(row) => (rowIdx = row.id)"
				@mouseLeaveCell="rowIdx = null"
				@selection-change="handleSelectionChange"
			>
				<!-- :fetch-list="amazonFbaInventoryPage" -->
				<template v-slot:tableLayout>
					<el-table-column type="selection" fixed="left"> </el-table-column>
					<el-table-column
						v-for="(col, ind) in columnsData.FBAInventoryList"
						:key="ind"
						:label="col.name"
						:prop="col.prop"
						:fixed="col.fixed ? col.fixed : false"
						:min-width="col.width ? col.width : '140'"
						:sortable="col.sortable"
					>
						<!-- th header -->
						<template #header>
							<div v-if="col.tooltip" style="display: flex; align-items: center">
								{{ col.name }}
								<el-tooltip effect="dark" :content="col.tooltip" placement="top">
									<el-icon><InfoFilled /></el-icon>
								</el-tooltip>
							</div>
							<span v-else>{{ col.name }}</span>
						</template>
						<template v-slot="scope">
							<template v-if="col.name === '仓库'">
								<div>
									{{ scope.row[col.prop] }}
									<span @click="() => copyText(scope.row[col.prop])">
										<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
											<DocumentCopy />
										</el-icon>
									</span>
								</div>
								<el-tag v-if="scope.row[col.prop]" style="margin-top: 12px" type="success"> FBA仓 </el-tag>
							</template>
							<template v-if="col.name === '图片'">
								<ewt-image
									:url="scope.row[col.prop]"
									style="width: 36px; height: 36px; object-fit: contain; display: block; cursor: pointer"
									@click="showImageViewer(scope.row[col.prop])"
								/>
							</template>
							<template v-if="col.name === 'ASIN'">
								<el-link :href="scope.row.asinUrl" target="_blank" type="primary">{{ scope.row.asin || '--' }}</el-link>
								<!-- &nbsp;
								<span @click="() => copyText(scope.row[col.prop])">
									<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
										<DocumentCopy />
									</el-icon>
								</span> -->
							</template>
							<template v-if="col.name === 'MSKU/FNSKU'">
								<div>
									{{ scope.row.msku || '--' }}
								</div>
								<div style="margin-top: 16px">
									{{ scope.row.fnsku || '--' }}
								</div>
							</template>
							<template v-if="col.name === '品名/SKU'">
								<div>
									{{ scope.row.prodName || '--' }}
									<span v-if="scope.row.fnsku" @click="() => copyText(scope.row.prodName)">
										<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
											<DocumentCopy />
										</el-icon>
									</span>
								</div>
								<div style="margin-top: 16px">
									{{ scope.row.skuCode || '--' }}
									<span v-if="scope.row.skuCode" @click="() => copyText(scope.row.skuCode)">
										<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
											<DocumentCopy />
										</el-icon>
									</span>
								</div>
							</template>
							<template v-if="col.name === '产品品牌/分类'">
								<div>{{ scope.row.skuBrandName || '--' }}</div>
								<div style="margin-top: 16px">{{ scope.row.skuCategoryName || '--' }}</div>
							</template>
							<template v-if="col.name === '配送方式/销售负责人'">
								<div v-if="!scope.row.deliveryChannel">{{ '--' }}</div>
								<template v-else>
									<span v-for="item in state.deliveryChannelList" :key="item.id" v-show="item.value === scope.row.deliveryChannel">
										{{ item.label }}
									</span>
								</template>
								<div style="margin-top: 16px">{{ scope.row.saleDutyUidNames || '--' }}</div>
							</template>
							<template v-if="col.name === '属性'">
								<div v-if="JSON.parse(scope.row[col.prop] || 'null')">
									<div v-for="(item, index) in JSON.parse(scope.row[col.prop])" :key="index">{{ item.attrKeyName }} : {{ item.attrValue }}</div>
								</div>
								<div v-else>--</div>
							</template>
							<template v-if="col.name === '入库中库存' || col.name === '预留库存' || col.name === '不可售库存' || col.name === '调查中库存'">
								<span v-if="!scope.row[col.prop] || scope.row[col.prop] === '0'">
									{{ scope.row[col.prop] }}
								</span>
								<el-popover v-else-if="scope.row[col.prop] > 0" placement="bottom" trigger="click" width="240px">
									<template #reference>
										<span style="cursor: pointer">
											{{ scope.row[col.prop] }}
											<el-icon><ArrowDown /></el-icon>
										</span>
									</template>
									<template v-if="col.name === '入库中库存'">
										<div><span style="color: #888">处理中 :</span> {{ scope.row.inboundWorkingQuantity }}</div>
										<div style="margin-top: 10px"><span style="color: #888">已发货 :</span> {{ scope.row.inboundShippedQuantity }}</div>
										<div style="margin-top: 10px"><span style="color: #888">正在接收 :</span> {{ scope.row.inboundReceivingQuantity }}</div>
									</template>
									<template v-else-if="col.name === '预留库存'">
										<div><span style="color: #888">卖家订单 :</span> {{ scope.row.pendingCustomerOrderQuantity }}</div>
										<div style="margin-top: 10px">
											<span style="color: #888">亚马逊运营中心转运 :</span> {{ scope.row.pendingTransshipmentQuantity }}
										</div>
										<div style="margin-top: 10px"><span style="color: #888">亚马逊运营中心处理中 :</span> {{ scope.row.fcProcessingQuantity }}</div>
									</template>
									<template v-else-if="col.name === '不可售库存'">
										<div><span style="color: #888">在库房出现残损 :</span> {{ scope.row.warehouseDamagedQuantity }}</div>
										<div style="margin-top: 10px"><span style="color: #888">买家导致残损 :</span> {{ scope.row.customerDamagedQuantity }}</div>
										<div style="margin-top: 10px"><span style="color: #888">因承运人导致的残损 :</span> {{ scope.row.carrierDamagedQuantity }}</div>
										<div style="margin-top: 10px">
											<span style="color: #888">因分销商导致的残损 :</span> {{ scope.row.distributorDamagedQuantity }}
										</div>
										<div style="margin-top: 10px"><span style="color: #888">存在瑕疵 :</span> {{ scope.row.defectiveQuantity }}</div>
										<div style="margin-top: 10px"><span style="color: #888">已过期 :</span> {{ scope.row.expiredQuantity }}</div>
									</template>
									<template v-else-if="col.name === '调查中库存'">
										<div><span style="color: #888">短期1-10天 :</span> {{ scope.row.researchingQuantityInshorterm }}</div>
										<div style="margin-top: 10px"><span style="color: #888">中期11-20天 :</span> {{ scope.row.researchingQuantityInmidterm }}</div>
										<div style="margin-top: 10px">
											<span style="color: #888">长期21天或以上 :</span> {{ scope.row.researchingQuantityInlongterm }}
										</div>
									</template>
								</el-popover>
							</template>
							<template v-if="col.name === '271~330天库龄' || col.name === '331~365天库龄' || col.name === '365+天库龄'">
								<div>{{ scope.row[col.prop] }}</div>
								<div v-if="scope.row[col.prop] > 0" style="margin-top: 16px">
									<span style="color: #888">超龄附加费 </span>
									<span v-if="col.name === '271~330天库龄'">{{ scope.row.currencySymbol }}{{ scope.row.stockAge330Fee }}</span>
									<span v-else-if="col.name === '331~365天库龄'">{{ scope.row.currencySymbol }}{{ scope.row.stockAge365Fee }}</span>
									<span v-else-if="col.name === '365+天库龄'">{{ scope.row.currencySymbol }}{{ scope.row.stockAgeOver365Fee }}</span>
								</div>
							</template>
						</template>
					</el-table-column>
				</template>
			</table-layout>
		</div>

		<ColumnsSetting
			ref="columnsSettingRef"
			@changeColumn="changeColumn"
			:allList="columns['FBAInventoryList']"
			commitName="FBAInventoryList"
			:list="columnsData['FBAInventoryList']"
		/>
		<ewt-image-viewer v-if="state.imageViewer" :url-list="[state.imageViewer]" @close="closeViewer" />
	</div>
</template>
<script lang="ts" setup  name="FBAInventory">
import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';
import { columns } from '../columnsSetting/columns.js';
import { getwhTree, treeQuery, getBrandList, amazonFbaInventoryPage, exportFbaInventory } from '../api.ts';
import { useDict } from '/@/hooks/dict';
const { listing_delivery_channel } = useDict('listing_delivery_channel');
import CommonFunction from '/@/utils/commonFunction';
const { copyText } = CommonFunction();
const rowIdx = ref(null);

const obj = {
	whIds: [],
	skuCategoryList: [],
	skuBrandList: [],
	deliveryChannelList: [],
	saleDutyUidList: [],
	searchDto: {},
	isHideZero: '1',
};
const state = reactive({
	selectedWhIdsList: [],
	checkedRows: [],
	queryForm: Object.assign({}, obj),
	imageViewer: '',
	FBAlist: [],
	// skuCategoryList: [],
	skuBrandList: [],
	deliveryChannelList: listing_delivery_channel,
	comboSearchOpt: [
		{ label: 'SKU', key: 'skuCode' },
		{ label: '品名', key: 'prodName' },
		{ label: 'MSKU', key: 'msku' },
		{ label: 'FNSKU', key: 'fnsku' },
		{ label: 'ASIN', key: 'asin' },
		{ label: 'SPU', key: 'spuCode' },
	],
});
const clearDto = () => {
	state.queryForm.searchDto = {};
	comboSearchRef.value?.resetFields();
};
const filterTags = reactive({
	whIds: [],
	saleDutyUidList: [],
	skuCategoryList: [],
});
const FilterTagOption = [
	{
		key: () => state.queryForm.whIds.length,
		label: () => 'FBA仓库',
		value: () => state.selectedWhIdsList.map((item) => item.label),
		clear: () => {
			state.queryForm.whIds = [];
		},
	},

	{
		key: () => state.queryForm.skuCategoryList.length,
		label: () => '产品分类',
		value: () => filterTags.skuCategoryList.map((item) => item.label),
		clear: () => {
			state.queryForm.skuCategoryList = [];
		},
	},
	{
		key: () => state.queryForm.skuBrandList.length,
		label: () => '产品品牌',
		value: () => state.skuBrandList.filter((item) => state.queryForm.skuBrandList.indexOf(item.brandId) !== -1).map((item) => item.brandName),
		clear: () => {
			state.queryForm.skuBrandList = [];
		},
	},
	{
		key: () => state.queryForm.deliveryChannelList.length,
		label: () => '配送方式',
		value: () => state.deliveryChannelList.filter((item) => state.queryForm.deliveryChannelList.indexOf(item.key) !== -1).map((item) => item.label),
		clear: () => {
			state.queryForm.deliveryChannelList = [];
		},
	},
	{
		key: () => state.queryForm.saleDutyUidList.length,
		label: () => '销售负责人',
		value: () => filterTags.saleDutyUidList.map((item) => item.name),
		clear: () => {
			state.queryForm.saleDutyUidList = [];
		},
	},
	{
		key: () => state.queryForm.searchDto?.searchFieldId,
		label: () => state.comboSearchOpt.find((item) => item.key === state.queryForm.searchDto?.searchFieldId)?.label,
		value: () => state.queryForm.searchDto?.searchValueList,
		clear: clearDto,
	},
];
const closeTag = (claar) => {
	claar();
	toRefresh();
};
const searchCategory = (ids, items) => {
	state.selectedWhIdsList = items;
	handleSearch(ids, 'whIds');
};
onMounted(() => {
	getwhTreeOpt();
	getSelectData();
});
const handleSelectionChange = (val) => {
	state.checkedRows = val;
};
const showImageViewer = (img) => {
	state.imageViewer = img;
};
const closeViewer = () => {
	state.imageViewer = '';
};

// 产品分类
const getSelectData = async () => {
	getBrandList({ current: 1, size: 1000 }).then((res) => {
		state.skuBrandList = res.data.records;
		state.skuBrandList.forEach((item) => {
			item.brandId = Number(item.brandId);
		});
	});
};

// 获取仓库树形结构
const getwhTreeOpt = async () => {
	const { data } = await getwhTree({ whTypeList: [4] });
	state.FBAlist = formatWhTree(data);
};
// 初始化仓库树形结构
const formatWhTree = (data) => {
	return data.map((item) => {
		item.key = item.nodeCode;
		item.label = item.nodeName;
		if (item.children) {
			item.children = formatWhTree(item.children);
		}
		return item;
	});
};
const toExport = () => {
	try {
		let ids = state.checkedRows.map((item) => {
			return item.id;
		});
		exportFbaInventory({ query: state.queryForm, amazonFbaInventoryIdList: ids }).then(() => {
			ElMessage({
				message: 'FBA库存下载成功，请至【下载中心】下载查看',
				type: 'success',
			});
		});
	} catch (res) {
		ElMessage({
			message: res.msg,
			type: 'error',
		});
	}
};
const handleSearch = (data, type) => {
	const { ids, list } = data;
	filterTags[type] = list;
	toRefresh();
};
const handleComboSearch = (ids, type) => {
	state.queryForm[type] = {};
	const { key, like, value } = ids;
	state.queryForm[type].searchFieldId = key;
	state.queryForm[type].searchValue = like;
	state.queryForm[type].searchValueList = value;
	state.queryForm[type].searchMode = value.length ? 'mode_in' : 'mode_like';

	toRefresh();
};
const columnsSettingRef = ref();
const comboSearchRef = ref();
const dataTableRef = ref();
// 列设置
const columnsData = reactive({
	FBAInventoryList: Local.get('FBAInventoryList') || columns.FBAInventoryList,
});
const changeColumn = (list) => {
	columnsData.FBAInventoryList = list;
};
const resetList = () => {
	Object.keys(obj).forEach((i) => {
		state.queryForm[i] = obj[i];
	});
	comboSearchRef.value?.resetFields();
	toRefresh();
};
const toRefresh = (v) => {
	dataTableRef.value.refresh(v);
};
const getSummaries = (param: SummaryMethodProps) => {
	const { columns, data } = param;
	const sums: string[] = [];
	columns.forEach((column, index) => {
		let sunThs = [
			'总库存',
			'可用库存',
			'入库中库存',
			'预留库存',
			'不可售库存',
			'调查中库存',
			'0~30天库龄',
			'31~60天库龄',
			'61~90天库龄',
			'91~180天库龄',
			'181~270天库龄',
			'271~330天库龄',
			'331~365天库龄',
			'365+天库龄',
		];
		if (sunThs.includes(column.label)) {
			const values = data.map((item) => Number(item[column.property]));
			if (!values.every((value) => Number.isNaN(value))) {
				sums[index] = `${values.reduce((prev, curr) => {
					let value = Number(curr);
					if (!Number.isNaN(value)) {
						return prev + curr;
					} else {
						return prev;
					}
				}, 0)}`;
			} else {
				sums[index] = '';
			}
		}
	});
	// 单独处理
	sums[0] = '总计';
	return sums;
};
</script>
<style scoped>
:deep(.fast-tabel-handle .right-content .base-right) {
	align-items: center;
}
</style>